
<template>
  <div class="shopping-cart">
    <div class="cart-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <el-button type="text" @click="goBack" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>购物车</h2>
      </div>

      <!-- 购物车内容 -->
      <div class="cart-content" v-loading="cartStore.loading">
        <!-- 空购物车状态 -->
        <div v-if="cartStore.cartItems.length === 0" class="empty-cart">
          <el-empty description="购物车是空的">
            <el-button type="primary" @click="goToHome">去购物</el-button>
          </el-empty>
        </div>

        <!-- 购物车商品列表 -->
        <div v-else class="cart-list">
          <!-- 全选操作栏 -->
          <div class="select-all-bar">
            <el-checkbox
                v-model="allSelected"
                @change="handleSelectAll"
                :indeterminate="indeterminate"
            >
              全选
            </el-checkbox>
            <span class="selected-count">已选择 {{ cartStore.selectedCount }} 件商品</span>
            <el-button
                type="text"
                @click="handleDeleteSelected"
                :disabled="cartStore.selectedCount === 0"
                class="delete-selected-btn"
            >
              删除选中
            </el-button>
          </div>

          <!-- 商品列表 -->
          <div class="cart-items">
            <div
                v-for="item in cartStore.cartItems"
                :key="item.cartId"
                class="cart-item"
            >
              <div class="item-selection">
                <el-checkbox
                    v-model="item.selected"
                    @change="handleItemSelect"
                />
              </div>

              <div class="item-image">
                <img :src="item.image || '/src/views/user/images/default-product.jpg'" :alt="item.productName" />
              </div>

              <div class="item-info">
                <div class="item-name">{{ item.productName }}</div>
                <div class="item-specs">
                  <span v-if="item.model">型号：{{ item.model }}</span>
                  <span v-if="item.color">颜色：{{ item.color }}</span>
                </div>
                <div class="item-status" :class="{ 'out-of-stock': item.productStatus !== 1 }">
                  {{ item.productStatus === 1 ? '现货' : '缺货' }}
                </div>
              </div>

              <div class="item-price">
                <span class="current-price">¥{{ item.price }}</span>
              </div>

              <div class="item-quantity">
                <el-input-number
                    v-model="item.quantity"
                    :min="1"
                    :max="999"
                    :disabled="item.productStatus !== 1"
                    @change="(value) => handleQuantityChange(item.cartId, value)"
                    size="small"
                />
              </div>

              <div class="item-total">
                <span class="total-price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
              </div>

              <div class="item-actions">
                <el-button
                    type="text"
                    @click="handleDeleteItem(item.cartId)"
                    class="delete-btn"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 结算栏 -->
      <div v-if="cartStore.cartItems.length > 0" class="checkout-bar">
        <div class="checkout-info">
          <div class="total-info">
            <span>总计：</span>
            <span class="total-price">¥{{ cartStore.selectedTotalPrice.toFixed(2) }}</span>
          </div>
          <div class="selected-info">
            已选择 {{ cartStore.selectedCount }} 件商品
          </div>
        </div>
        <el-button
            type="danger"
            size="large"
            :disabled="cartStore.selectedCount === 0"
            @click="handleCheckout"
            class="checkout-btn"
        >
          结算 ({{ cartStore.selectedCount }})
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/store/cart'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

const router = useRouter()
const cartStore = useCartStore()

// 全选状态
const allSelected = computed({
  get() {
    return cartStore.cartItems.length > 0 && cartStore.cartItems.every(item => item.selected)
  },
  set(value) {
    cartStore.toggleAllSelection(value)
  }
})

// 半选状态
const indeterminate = computed(() => {
  const selectedCount = cartStore.selectedCount
  return selectedCount > 0 && selectedCount < cartStore.cartItems.length
})

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 去首页购物
const goToHome = () => {
  router.push('/user/home')
}

// 处理全选
const handleSelectAll = (value) => {
  cartStore.toggleAllSelection(value)
}

// 处理单个商品选择
const handleItemSelect = () => {
  // 选择状态已经通过 v-model 更新了
}

// 处理数量变更
const handleQuantityChange = (cartId, quantity) => {
  if (quantity < 1) return
  cartStore.updateItemQuantity(cartId, quantity)
}

// 删除单个商品
const handleDeleteItem = async (cartId) => {
  try {
    await ElMessageBox.confirm('确定要删除这件商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await cartStore.removeItem(cartId)
  } catch (error) {
    // 用户取消删除
  }
}

// 删除选中商品
const handleDeleteSelected = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${cartStore.selectedCount} 件商品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await cartStore.removeSelectedItems()
  } catch (error) {
    // 用户取消删除
  }
}

// 结算
const handleCheckout = () => {
  const selectedItems = cartStore.cartItems.filter(item => item.selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }

  // 跳转到结算页面
  router.push({
    path: '/user/checkout',
    query: {
      items: JSON.stringify(selectedItems.map(item => ({
        cartId: item.cartId,
        productId: item.productId,
        productName: item.productName,
        price: item.price,
        quantity: item.quantity,
        image: item.image
      })))
    }
  })
}

// 页面加载时获取购物车数据
onMounted(() => {
  cartStore.fetchCartList()
})
</script>

<style scoped>
.shopping-cart {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
}

.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 页面头部 */
.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.back-btn {
  margin-right: 15px;
  color: #666;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

/* 购物车内容 */
.cart-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

/* 空购物车 */
.empty-cart {
  padding: 60px 20px;
  text-align: center;
}

/* 全选操作栏 */
.select-all-bar {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.selected-count {
  margin-left: 20px;
  color: #666;
  font-size: 14px;
}

.delete-selected-btn {
  margin-left: auto;
  color: #ff4d4f;
}

.delete-selected-btn:disabled {
  color: #ccc;
}

/* 购物车商品列表 */
.cart-items {
  padding: 0;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.cart-item:hover {
  background-color: #fafafa;
}

.cart-item:last-child {
  border-bottom: none;
}

/* 商品选择 */
.item-selection {
  width: 40px;
  margin-right: 15px;
}

/* 商品图片 */
.item-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 4px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商品信息 */
.item-info {
  flex: 1;
  margin-right: 20px;
}

.item-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
}

.item-specs {
  display: flex;
  gap: 15px;
  margin-bottom: 5px;
}

.item-specs span {
  font-size: 12px;
  color: #999;
}

.item-status {
  font-size: 12px;
  color: #52c41a;
}

.item-status.out-of-stock {
  color: #ff4d4f;
}

/* 商品价格 */
.item-price {
  width: 100px;
  text-align: center;
  margin-right: 20px;
}

.current-price {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: bold;
}

/* 商品数量 */
.item-quantity {
  width: 120px;
  margin-right: 20px;
}

/* 商品小计 */
.item-total {
  width: 100px;
  text-align: center;
  margin-right: 20px;
}

.total-price {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: bold;
}

/* 商品操作 */
.item-actions {
  width: 80px;
  text-align: center;
}

.delete-btn {
  color: #999;
}

.delete-btn:hover {
  color: #ff4d4f;
}

/* 结算栏 */
.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  padding: 15px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 -2px 8px rgba(0,0,0,0.1);
  z-index: 1000;
}

.checkout-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.total-info {
  font-size: 16px;
}

.total-info .total-price {
  font-size: 20px;
  color: #ff4d4f;
  font-weight: bold;
  margin-left: 10px;
}

.selected-info {
  font-size: 12px;
  color: #666;
}

.checkout-btn {
  min-width: 120px;
  height: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cart-container {
    padding: 10px;
  }

  .cart-item {
    flex-wrap: wrap;
    padding: 15px;
  }

  .item-info {
    width: 100%;
    margin: 10px 0;
  }

  .item-price,
  .item-quantity,
  .item-total {
    width: auto;
    margin: 5px 10px;
  }

  .checkout-bar {
    padding: 10px;
    flex-direction: column;
    gap: 10px;
  }

  .checkout-info {
    width: 100%;
    text-align: center;
  }
}
</style>
